package com.zhaiker.keypointestimationlibrary

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.lifecycle.ViewModel
import com.cv.tnn.model2.Detector
import com.cv.tnn.model2.FrameInfo
import com.zhaiker.keypointestimation.KeypointEstimationHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.InputStream

class MainViewModel : ViewModel() {

    /**
     * 读取Assets的图片
     */
    private suspend fun getBitmapFromAssets(context: Context, fileName: String): Bitmap? = withContext(
        Dispatchers.IO){
        var inputStream: InputStream? = null
        var bitmap: Bitmap? = null

        try {
            // 打开assets目录中的文件流
            inputStream = context.assets.open(fileName)
            // 将流解码为Bitmap
            bitmap = BitmapFactory.decodeStream(inputStream)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                inputStream?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        return@withContext bitmap
    }

    suspend fun poseDetect(context: Context) : Array<FrameInfo> = withContext(Dispatchers.IO){
        val bmp = getBitmapFromAssets(context,"test.png")
        val startTime = System.currentTimeMillis()
        val res = KeypointEstimationHelper.detect(bmp!!)
        val endTime = System.currentTimeMillis()
        println("poseDetect time: ${endTime - startTime}")
        return@withContext res
    }

}